<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="100px">
      <el-row>
        <el-col :span="16">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="dataForm.roleName" placeholder="角色名称"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="所属部門" prop="deptName">
            <el-popover
              ref="menuListPopover"
              placement="bottom-start"
              trigger="click">
              <el-tree
                :data="deptRoleList"
                :props="deptRoleListTreeProps"
                node-key="deptId"
                ref="deptRoleListTree"
                @current-change="deptRoleListTreeCurrentChangeHandle"
                :default-expand-all="true"
                :highlight-current="true"
                :expand-on-click-node="false">
              </el-tree>
            </el-popover>
            <el-input v-model="dataForm.deptName" v-popover:menuListPopover :readonly="true" placeholder="点击选择部门菜单"
                      class="dept-list__input"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="dataForm.remark" placeholder="备注"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>

        <el-col :span="10">
          <el-form-item size="small" label="菜单">
            <el-tree
              :data="menuAllList"
              :props="menuAllListTreeProps"
              node-key="menuId"
              ref="menuAllListTree"
              :default-expand-all="true"
              show-checkbox>
            </el-tree>
          </el-form-item>
        </el-col>

        <el-col :span="10">
          <el-form-item size="small" label="数据">
            <el-tree
              :data="deptList"
              :props="deptListTreeProps"
              node-key="deptId"
              ref="deptListTree"
              :default-expand-all="true"
              show-checkbox>
            </el-tree>
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import {treeDataTranslate} from '@/utils'

  export default {
    data () {
      return {
        visible: false,
        menuAllList: [],
        menuAllListTreeProps: {
          label: 'name',
          children: 'children'
        },
        deptList: [],
        deptListTreeProps: {
          label: 'name',
          children: 'children'
        },
        dataForm: {
          id: 0,
          roleName: '',
          deptName: '',
          deptId: null,
          remark: ''
        },
        dataRule: {
          roleName: [
            {required: true, message: '角色名称不能为空', trigger: 'blur'}
          ]
        },
        deptRoleList: [],
        deptRoleListTreeProps: {
          label: 'name',
          children: 'children'
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.$http({
          url: this.$http.adornUrl('/sys/menu/list'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          this.menuAllList = treeDataTranslate(data, 'menuId')
          this.deptListTreeCurrentChangeHandle()
        }).then(() => {
          this.visible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
            this.$refs.menuAllListTree.setCheckedKeys([])
            this.$refs.deptListTree.setCheckedKeys([])
            this.$refs.deptRoleListTree.setCheckedKeys([])
          })
        }).then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/sys/role/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.roleName = data.role.roleName
                this.dataForm.remark = data.role.remark
                this.dataForm.deptId = data.role.deptId
                this.dataForm.deptName = data.role.deptName
                console.log(data.role.menuIdList)
                console.log(data.role.deptIdList)
                // 设置菜单选中 原来是因为这里后端返回最顶级的树节点（parentId） 导致树无法默认选中,后端中代码去掉了parent_id=0的节点
                this.$refs.menuAllListTree.setCheckedKeys(data.role.menuIdList)
                // 设置角色中的部门树形菜单选中
                this.$refs.deptListTree.setCheckedKeys(data.role.deptIdList)
                this.deptRoleListTreeSetCurrentNode()
              }
            })
          }
        })
      },
      // 加载部门树
      deptListTreeCurrentChangeHandle () {
        this.$http({
          url: this.$http.adornUrl(`/sys/dept/list`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          console.log('加载部门数据成功')
          console.log(data)
          if (data && data.code === 0) {
            const deptListOnlyOne = treeDataTranslate(data.deptList, 'deptId')
            this.deptList = deptListOnlyOne
            this.deptRoleList = deptListOnlyOne
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      // 菜单树选中
      deptRoleListTreeCurrentChangeHandle (data, node) {
        console.log('菜单树选中')
        console.log(data)
        this.dataForm.deptId = data.deptId
        this.dataForm.deptName = data.name
      },
      // 菜单树设置当前选中节点
      deptRoleListTreeSetCurrentNode () {
        if (this.dataForm.deptId) {
          console.log('菜单树设置当前选中节点')
          this.$refs.deptRoleListTree.setCurrentKey(this.dataForm.deptId)
          this.dataForm.deptName = (this.$refs.deptRoleListTree.getCurrentNode() || {})['name']
        }
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            console.log([].concat(this.$refs.menuAllListTree.getCheckedKeys(), this.$refs.menuAllListTree.getHalfCheckedKeys()))
            this.$http({
              url: this.$http.adornUrl(`/sys/role/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'roleId': this.dataForm.id || undefined,
                'roleName': this.dataForm.roleName,
                'remark': this.dataForm.remark,
                'deptId': this.dataForm.deptId,
                // this.$refs.menuAllListTree.getHalfCheckedKeys() 1、2级菜单也要传给后端 不然导致菜单无法显示
                'menuIdList': [].concat(this.$refs.menuAllListTree.getCheckedKeys(), this.$refs.menuAllListTree.getHalfCheckedKeys()),
                'deptIdList': [].concat(this.$refs.deptListTree.getCheckedKeys())
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
